using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LP;
using System.Threading;

public sealed class CoroutineMgr : AbsMgr, ICancleTokener
{
    private sealed class CoroutineWrap
    {
        public Coroutine Coroutine { get; private set; }
        public CancellationToken CancellationToken { get; private set; }
        public CoroutineWrap(Coroutine coroutine, CancellationToken cancellationToken)
        {
            Coroutine = coroutine;
            CancellationToken = cancellationToken;
        }
    }

    private List<CoroutineWrap> coroutineWraps = new List<CoroutineWrap>();

    public override void OnDestroy()
    {
        foreach (var item in coroutineWraps)
        {
            if (item.CancellationToken.IsCancellationRequested && item.Coroutine != null)
            {
                Global.MainBehaviour.StopCoroutine(item.Coroutine);
            }
        }
        coroutineWraps.Clear();
        base.OnDestroy();
    }

    public Coroutine StartCoroutine(IEnumerator ienumerator, CancellationToken cancellationToken)
    {
        try
        {
            Coroutine coroutine = Global.MainBehaviour.StartCoroutine(ienumerator);
            coroutineWraps.Add(new CoroutineWrap(coroutine, cancellationToken));
            return coroutine;
        }
        catch (System.Exception e)
        {
            Debug.LogError(e);
            return null;
        }
    }

    public void StopCoroutine(Coroutine coroutine)
    {
        if (coroutine == null)
        {
            return;
        }
        for (int i = 0; i < coroutineWraps.Count; i++)
        {
            var item = coroutineWraps[i];
            if (item.Coroutine != null && item.Coroutine == coroutine)
            {
                Global.MainBehaviour.StopCoroutine(coroutine);
                coroutineWraps.Remove(item);
                break;
            }
        }
    }

    public void OnCancleToken()
    {
        for (int i = 0; i < coroutineWraps.Count; i++)
        {
            var coroutineWrap = coroutineWraps[i];
            if (coroutineWrap.CancellationToken.IsCancellationRequested)
            {
                if (coroutineWrap.Coroutine != null)
                {
                    Global.MainBehaviour.StopCoroutine(coroutineWrap.Coroutine);
                }
                coroutineWraps.Remove(coroutineWrap);
            }
        }
    }
    
}
